package com.niit.springbootshop.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * @program: shop-teacher
 * @description:
 * @author: hanliang
 * @create: 2021-05-08 00:43
 **/
@Service
public class MailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    //template模板引擎
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 发送简单邮件（纯文本邮件)
     * @param tos     收件人数组
     * @param subject 邮件主题
     * @param content 邮件内容
     * @return
     */
    @Async
    public boolean commonEmail(String[] tos, String subject, String content) {
        //创建简单邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        //谁发的
        message.setFrom(from);
        //谁要接收
        message.setTo(tos);
        //邮件标题
        message.setSubject(subject);
        //邮件内容
        message.setText(content);
        try {
            javaMailSender.send(message);
            return true;
        } catch (MailException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 发送模板邮件
     *
     * @param tos     收件人数组
     * @param subject 邮件主题
     * @param data 邮件内容
     * @return
     */
    @Async
    public boolean sendTemplateMail(String tos, String subject, Map<String,Object> data) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            messageHelper.setFrom(from);// 发送人的邮箱
            messageHelper.setTo(tos);//发给谁  对方邮箱
            messageHelper.setSubject(subject); //标题
            //使用模板thymeleaf
            //Context是导这个包import org.thymeleaf.context.Context;
            Context context = new Context();
            //定义模板数据
            context.setVariables(data);
            //获取thymeleaf的html模板
            String emailContent = templateEngine.process("mail/mail",context); //指定模板路径
            messageHelper.setText(emailContent,true);
            //发送邮件
            javaMailSender.send(mimeMessage);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }
}